package com.ff.kvm.mall.service.impl;

import cn.hutool.core.date.DateUtil;
import com.ff.kvm.common.dv.product.ProductDV;
import com.ff.kvm.common.dv.signin.*;
import com.ff.kvm.common.eunm.StatusEnum;
import com.ff.kvm.common.util.Constants;
import com.ff.kvm.common.vo.PageResult;
import com.ff.kvm.common.vo.Response;
import com.ff.kvm.dao.mapper.*;
import com.ff.kvm.dao.model.*;
import com.ff.kvm.dao.model.po.GiftPostage;
import com.ff.kvm.dao.model.po.PersonalProductPO;
import com.ff.kvm.dao.model.po.SigninGiftNodePO;
import com.ff.kvm.mall.service.RedisService;
import com.ff.kvm.mall.service.SignInService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class SignInServiceImpl implements SignInService {

    @Autowired
    private RedisService redisService;
    @Autowired
    private SignInMapper signInMapper;
    @Autowired
    private SysCodeMapper sysCodeMapper;
    @Autowired
    private PersonalGiftMapper personalGiftMapper;
    @Autowired
    private ProductMapper productMapper;

    @Override
    public Response<String> getGiftPostage(Integer id) {
        Response<String> response = new Response();
        GiftPostage personalGift = personalGiftMapper.getGiftPostage(id);
        response.setData(personalGift.getPostage().toString());
        response.setCode(StatusEnum.SUCCESS.getCode());
        response.setMsg(StatusEnum.SUCCESS.getDescription());
        return response;
    }

    @Transactional
    @Override
    public Response<Boolean> getGift(Integer userId, Integer id) {
        Response<Boolean> response = new Response();
        //领取
        PersonalGift personalGift = personalGiftMapper.selectByPrimaryKey(id);
        personalGift.setGetStatus(1);
        personalGift.setGetTime(new Date());
        personalGift.setUpdateTime(new Date());
        personalGiftMapper.updateByPrimaryKey(personalGift);
        //领取计数
        int result = personalGiftMapper.giftNumCumulative(personalGift.getGiftId());
        response.setData(true);
        response.setCode(StatusEnum.SUCCESS.getCode());
        response.setMsg(StatusEnum.SUCCESS.getDescription());
        return response;
    }

    @Override
    public Response<SignStatusDV> signinStatus(Integer userId) {
        Response<SignStatusDV> response = new Response();
        SignStatusDV signstatus = new SignStatusDV();
        SignIn curdateStatus = signInMapper.signTodayStatus(userId);//当日签到数据
        if (curdateStatus != null) {
            signstatus.setCurdateIsSignin(true);//当日签到
        } else {
            signstatus.setCurdateIsSignin(false);
        }
        if (curdateStatus == null) {
            curdateStatus = signInMapper.getLastSinginInfo(userId);//昨日连续签到的数据
        }
        if (curdateStatus != null) {
            signstatus.setNum(curdateStatus.getSigninNo());
        } else {
            signstatus.setNum(0);
        }
        response.setData(signstatus);
        response.setCode(StatusEnum.SUCCESS.getCode());
        response.setMsg(StatusEnum.SUCCESS.getDescription());
        return response;
    }

    @Override
    public Response<PageResult<PersonalProductDV>> personalGiftList(Integer userId, Integer PageNum, Integer status) {
        Response<PageResult<PersonalProductDV>> response = new Response();
        PageResult<PersonalProductDV> result = new PageResult<>();
        int pageSize = Integer.valueOf(redisService.getCache(Constants.PAGE_SIZE));
        List<ProductDV> listDV = new ArrayList();
        Page page = PageHelper.startPage(PageNum, pageSize);
        List<PersonalProductDV> ppdvList = new ArrayList();
        List<PersonalProductPO> pppoList = personalGiftMapper.personalGiftList(userId, status);
        for (PersonalProductPO personalProductPO : pppoList) {
            PersonalProductDV personalProductDV = new PersonalProductDV();
            personalProductDV.setDes(personalProductPO.getDes());
            personalProductDV.setCreateTime(DateUtil.format(personalProductPO.getCreateTime(), "yyyy-MM-dd"));
            personalProductDV.setGetStatus(personalProductPO.getGetStatus());
            personalProductDV.setGiftId(personalProductPO.getGiftId());
            personalProductDV.setIcon(personalProductPO.getIcon());
            personalProductDV.setGetTime(DateUtil.format(personalProductPO.getGetTime(), "yyyy-MM-dd"));
            personalProductDV.setId(personalProductPO.getId());
            personalProductDV.setPrice(personalProductPO.getPrice());
            personalProductDV.setUserId(personalProductPO.getUserId());
            personalProductDV.setName(personalProductPO.getName());
            ppdvList.add(personalProductDV);
        }
        Long total = personalGiftMapper.personalGiftListTotal(userId, status);
        result.setTotal(total);
        result.setPageSize(page.getPageSize());
        result.setData(ppdvList);
        response.setData(result);
        response.setCode(StatusEnum.SUCCESS.getCode());
        response.setMsg(StatusEnum.SUCCESS.getDescription());
        return response;
    }

    @Override
    public Response<SigninGiftTimeNodeDV> signinGiftNode() {
        Response<SigninGiftTimeNodeDV> response = new Response();
        SigninGiftTimeNodeDV timeNode = new SigninGiftTimeNodeDV();
        SysCode code = sysCodeMapper.selectByPrimaryKey("sign_in_max_no");
        if (code != null) {
            timeNode.setSignInMaxNo(Integer.parseInt(code.getCode()));
        } else {
            timeNode.setSignInMaxNo(0);
        }
        List<SigninGiftNodePO> nodes = signInMapper.signinGiftSeting();
        if (nodes.size() > 0) {
            List<SigninGiftSetingDV> giftTimeNode = new ArrayList();
            for (int i = 0; i < nodes.size(); i++) {
                SigninGiftSetingDV setingdv = new SigninGiftSetingDV();
                SigninGiftNodePO nodepo = nodes.get(i);
                setingdv.setSigninNo(nodepo.getSigninNo());
                setingdv.setGiftProductId(nodepo.getGiftProductId());
                giftTimeNode.add(setingdv);
            }
            timeNode.setGiftTimeNode(giftTimeNode);
        }
        response.setData(timeNode);
        response.setCode(StatusEnum.SUCCESS.getCode());
        response.setMsg(StatusEnum.SUCCESS.getDescription());
        return response;
    }

    @Override
    @Transactional
    public Response<GetGiftDV> signIn(Integer userId) {
        Response<GetGiftDV> response = new Response();
        SignIn signStatus = signInMapper.signTodayStatus(userId);
        GetGiftDV getGiftDV = null;
        if (signStatus == null) {
            SysCode code = sysCodeMapper.selectByPrimaryKey("sign_in_max_no");
            SignIn per = new SignIn();
            per.setSigninTime(new Date());
            per.setUserId(userId);
            per.setSigninMaxNo(Integer.parseInt(code.getCode()));
            SignIn lastSignIn = signInMapper.getLastSinginInfo(userId);
            if (lastSignIn == null || (lastSignIn.getSigninNo() == Integer.parseInt(code.getCode()))) {
                per.setSigninNo(1);
            } else {
                per.setSigninNo(lastSignIn.getSigninNo() + 1);
            }
            signInMapper.insert(per);
            //连续签到达到设定天数赠送奖品
            List<SigninGiftNodePO> nodes = signInMapper.signinGiftSeting();
            //是否有签到礼物
            if (nodes.size() > 0) {
                for (int i = 0; i < nodes.size(); i++) {
                    if (per.getSigninNo() == nodes.get(i).getSigninNo()) {
                        getGiftDV = new GetGiftDV();
                        Integer productId = signInMapper.getPrdcutId(nodes.get(i).getGiftProductId());
                        Product product = productMapper.selectByPrimaryKey(productId);
                        getGiftDV.setName(product.getName());
                        getGiftDV.setIcon(product.getIcon());
                        getGiftDV.setDes(product.getRemark());
                        getGiftDV.setProductId(product.getId());
                        SysCode expiration_day = sysCodeMapper.selectByPrimaryKey("sign_in_expiration_day");
                        PersonalGift gift = new PersonalGift();
                        gift.setCreateTime(new Date());
                        gift.setUserId(userId);
                        gift.setGiftId(nodes.get(i).getGiftProductId());
                        gift.setGetStatus(0);
                        //设置过期时间
                        gift.setExpirationTime(getNextDate(new Date(), Integer.parseInt(expiration_day.getCode())));
                        personalGiftMapper.insert(gift);
                    }
                }
            }
            response.setCode(StatusEnum.SUCCESS.getCode());
            response.setMsg(StatusEnum.SUCCESS.getDescription());
            response.setData(getGiftDV);
        } else {
            response.setCode(StatusEnum.SIGNED_IN.getCode());
            response.setMsg(StatusEnum.SIGNED_IN.getDescription());
            response.setData(getGiftDV);
        }
        return response;
    }

    public Date getNextDate(Date per, Integer days) {
        DateFormat dft = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cld = Calendar.getInstance();
        cld.setTime(per);
        cld.add(Calendar.DATE, days);
        return cld.getTime();
    }

}
